import 'package:library_base/entities/buyer_entity.dart';
import 'package:library_base/entities/summary_child_entity.dart';
import 'package:library_base/entities/summary_entity.dart';
import 'package:library_base/entities/suppliers_entity.dart';
import 'package:library_base/entities/warehouse_entity.dart';
import 'package:library_base/net/apis.dart';
import 'package:library_base/network/http_config.dart';
import 'package:get/get.dart';
import 'package:library_base/provider/base_list_controller.dart';
import 'package:library_base/route/routers.dart';
import 'package:library_base/widget/dialog/dialog_util.dart';
import 'package:library_base/widget/multi_state_widget/multi_state_widget.dart';

class SummaryListController extends BaseListController<SummaryEntity, SummaryEntity> {
  /// 实体类
  RxList<SummaryChildEntity> listDataSelected = <SummaryChildEntity>[].obs;

  Rx<String> stationTimeBegin = ''.obs;

  Rx<String> stationTimeEnd = ''.obs;

  String consignee = '';

  ///是否全选
  Rx<bool> isSelectAll = false.obs;

  @override
  void onCreate() {
    enableLoadMore = false;
    isShowNoMoreFooter = false;
  }

  @override
  Future requestData() {
    isFirstLoading = true;
    requestGeneralListData(Apis.SUMMARY_OF_REQUIREMENTS,
        isRefresh: false,
        method: FBResultFul.GET,
        queryParameters: {
          "stationTimeBegin": stationTimeBegin.value,
          "stationTimeEnd": stationTimeBegin.value,
          "consignee": consignee,
        });
    return super.requestData();
  }

  @override
  List<SummaryEntity> transformList(List<SummaryEntity> dataList, bool isRefresh) {
    if (isRefresh) {
      listDataSelected.clear();
      isSelectAll.value = false;
    } else {
      if (dataList.isNotEmpty) {
        isSelectAll.value = false;
      }
    }

    for (int i = 0; i < dataList.length; i++) {
      var item = dataList[i];
      for (int j = 0; j < item.orderDetails.length; j++) {
        var itemChild = item.orderDetails[j];
        itemChild.goodsCode = item.goodsCode;
        itemChild.shipperId = item.shipperId;
      }
    }
    return super.transformList(dataList, isRefresh);
  }

  @override
  Future onRefreshCallback() async {
    requestGeneralListData(Apis.SUMMARY_OF_REQUIREMENTS,
        isRefresh: true,
        method: FBResultFul.GET,
        queryParameters: {
          "stationTimeBegin": stationTimeBegin.value,
          "stationTimeEnd": stationTimeBegin.value,
          "consignee": consignee,
        });
  }

  @override
  Future onLoadCallback() async {
    requestGeneralListData(Apis.SUMMARY_OF_REQUIREMENTS,
        isRefresh: false,
        method: FBResultFul.GET,
        queryParameters: {
          "stationTimeBegin": stationTimeBegin.value,
          "stationTimeEnd": stationTimeBegin.value,
          "consignee": consignee,
        });
  }

  void reset() {
    stationTimeBegin.value = '';
    stationTimeEnd.value = '';
    consignee = '';
    isFirstLoading = true;
    multiControllerOut.viewStateChange(MultiStateStatus.loading);
    baseState?.setStateCallBack?.call();
    requestGeneralListData(Apis.SUMMARY_OF_REQUIREMENTS,
        isRefresh: false,
        method: FBResultFul.GET,
        queryParameters: {
          "stationTimeBegin": stationTimeBegin.value,
          "stationTimeEnd": stationTimeBegin.value,
          "consignee": consignee,
        });
  }

  void filter(String time,String? consignee) {
    stationTimeBegin.value = time;
    this.consignee = consignee??"";
    stationTimeEnd.value = '';
    isFirstLoading = true;
    multiControllerOut.viewStateChange(MultiStateStatus.loading);
    baseState?.setStateCallBack?.call();
    requestGeneralListData(Apis.SUMMARY_OF_REQUIREMENTS,
        isRefresh: false,
        method: FBResultFul.GET,
        queryParameters: {
          "stationTimeBegin": stationTimeBegin.value,
          "stationTimeEnd": stationTimeBegin.value,
          "consignee": consignee,
        });
  }

  void tryReLoad() {
    isFirstLoading = true;
    multiControllerOut.viewStateChange(MultiStateStatus.loading);
    baseState?.setStateCallBack?.call();
    requestGeneralListData(Apis.SUMMARY_OF_REQUIREMENTS,
        isRefresh: false,
        method: FBResultFul.GET,
        queryParameters: {
          "stationTimeBegin": stationTimeBegin.value,
          "stationTimeEnd": stationTimeBegin.value,
          "consignee": consignee,
        });
  }

  void onItemClick(SummaryEntity itemData) {
    itemData.isSelect = !itemData.isSelect;

    for (int i = 0; i < itemData.orderDetails.length; i++) {
      var itemChild = itemData.orderDetails[i];
      if (!listDataSelected.value.contains(itemChild)) {
        listDataSelected.value.add(itemChild);
      } else {
        listDataSelected.value.remove(itemChild);
      }
    }
    isSelectAll.value = checkIsSelectAll();

    update();
  }

  void onExpand(SummaryEntity itemData) {
    itemData.isExpand = !itemData.isExpand;
    update();
  }

  void onTapChild(SummaryChildEntity itemData) {
    itemData.isSelect = !itemData.isSelect;

    if (!listDataSelected.value.contains(itemData)) {
      listDataSelected.value.add(itemData);
    } else {
      listDataSelected.value.remove(itemData);
    }

    isSelectAll.value = checkIsSelectAll();

    update();
  }

  void chooseBuyerPage() {
    // requestUniversal<BuyerEntity>(Apis.BUYER,
    //     method: FBResultFul.GET,
    //     queryParameters: {'postCode': "purchaser"}, resultSuccessListCall: (list) async {
    //   Get.toNamed(Routers.chooseSummaryBuyerPage, arguments: {'Buyer': list, 'callback': choose});
    // });
    var map = <String,dynamic>{};
    map["callback"] = createTask;
    DialogUtil.showFillInformationDialog(arguments: map);
  }

  void createTask(SuppliersEntity suppliersEntity,WarehouseEntity warehouse,String? remark) {
    List<dynamic> goodsDetails = [];
    Set s = {};
    for (int i = 0; i < listDataSelected.value.length; i++) {
      var itemChild = listDataSelected.value[i];
      s.add(itemChild.goodsCode);
    }

    for (int i = 0; i < s.toList().length; i++) {
      var goodsCode = s.toList()[i];
      var isAdd = false;
      for (int j = 0; j < listDataSelected.value.length; j++) {
        if (isAdd) {
          continue;
        }
        var itemChild = listDataSelected.value[j];
        if (itemChild.goodsCode == goodsCode) {
          List<String> orderIds = [];
          for (int h = 0; h < listDataSelected.value.length; h++) {
            var itemChildH = listDataSelected.value[h];
            if (itemChildH.goodsCode == goodsCode) {
              orderIds.add(itemChildH.orderId);
            }
          }
          Map<String, dynamic> map = {};
          map['goodsCode'] = goodsCode;
          map['shipperId'] = itemChild.shipperId;
          map['orderIds'] = orderIds;
          goodsDetails.add(map);
          isAdd = true;
        }
      }
    }
    requestUniversal<bool>(Apis.CREATE_FROM_DEMAND,
        params: {
          'warehouseId': warehouse.id,
          'supplierId': suppliersEntity.id,
          'remark': remark,
          'goodsDetails': goodsDetails,
        },
        tipSuccess: '创建采购任务成功',
        isShowToastTip: true,
        method: FBResultFul.POST, resultSuccessCall: (success) async {
      requestGeneralListData(Apis.SUMMARY_OF_REQUIREMENTS,
          isRefresh: true,
          method: FBResultFul.GET,
          queryParameters: {
            "stationTimeBegin": stationTimeBegin.value,
            "stationTimeEnd": stationTimeBegin.value,
            "consignee": consignee,
          });
    });
  }

  void selectedAll() {
    var totalGoods = 0;
    for (var element in listData.value) {
      totalGoods += element.orderDetails.length;
    }

    if (listDataSelected.length != totalGoods) {
      for (var element in listData.value) {
        element.isSelect = true;
      }
      listDataSelected.value.clear();
      for (var element in listData.value) {
        for (var elementChild in element.orderDetails) {
          elementChild.isSelect = true;
        }
        listDataSelected.addAll(element.orderDetails);
      }
      isSelectAll.value = listDataSelected.length == totalGoods;
      update();
    } else {
      for (var element in listData.value) {
        for (var elementChild in element.orderDetails) {
          elementChild.isSelect = false;
        }
        listDataSelected.addAll(element.orderDetails);
      }
      listDataSelected.value.clear();
      isSelectAll.value = listDataSelected.length == totalGoods;
      update();
    }
  }

  bool checkIsSelectAll() {
    var totalGoods = 0;
    for (var element in listData.value) {
      totalGoods += element.orderDetails.length;
    }
    return listDataSelected.length == totalGoods;
  }
}
